import { API_BASE_URL } from '../services/http';

export function tryParseUrl(url) {
  try { return new URL(url); } catch (_) { return null; }
}

export function allowedHosts() {
  const base = tryParseUrl(API_BASE_URL);
  const list = [
    'localhost:8123',
    'wu-wa-manus-1332372410.cos.ap-shanghai.myqcloud.com' // 添加腾讯云COS域名
  ];
  if (base && base.host && !list.includes(base.host)) list.push(base.host);
  return list;
}

export function isAllowedUrl(url) {
  const u = tryParseUrl(url);
  if (!u) return false;
  return allowedHosts().includes(u.host);
}

export function getFileNameFromUrl(url) {
  const u = tryParseUrl(url);
  if (!u) return '文件.pdf';
  const pathname = u.pathname || '';
  const name = pathname.substring(pathname.lastIndexOf('/') + 1) || '文件.pdf';
  try { return decodeURIComponent(name); } catch (_) { return name; }
}

export function formatBytes(bytes) {
  if (bytes == null || isNaN(bytes)) return '—';
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = Number(bytes);
  let i = 0;
  while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
  return `${size.toFixed(size < 10 && i > 0 ? 1 : 0)} ${units[i]}`;
}

